const { testConnection, query } = require('./config/database');
require('dotenv').config();

// 测试数据库连接和基本查询
async function runTests() {
  console.log('🔍 开始数据库连接测试...\n');

  try {
    // 测试连接
    console.log('1. 测试数据库连接...');
    const connected = await testConnection();
    
    if (!connected) {
      console.log('❌ 数据库连接失败');
      return;
    }

    // 测试基本查询
    console.log('2. 测试基本查询...');
    const tables = await query('SHOW TABLES');
    console.log(`✅ 数据库中共有 ${tables.length} 个表:`);
    tables.forEach(table => {
      const tableName = Object.values(table)[0];
      console.log(`   - ${tableName}`);
    });

    // 测试数据查询
    console.log('\n3. 测试数据查询...');
    
    const userCount = await query('SELECT COUNT(*) as count FROM users');
    console.log(`   用户数量: ${userCount[0].count}`);
    
    const songCount = await query('SELECT COUNT(*) as count FROM songs');
    console.log(`   歌曲数量: ${songCount[0].count}`);
    
    const artistCount = await query('SELECT COUNT(*) as count FROM artists');
    console.log(`   歌手数量: ${artistCount[0].count}`);

    console.log('\n🎉 所有测试通过！数据库配置正确。');

  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    console.log('\n请检查以下配置:');
    console.log('1. MySQL服务是否启动');
    console.log('2. .env文件中的数据库配置是否正确');
    console.log('3. 数据库是否已创建');
    console.log('4. 用户权限是否足够');
  }
}

// 运行测试
if (require.main === module) {
  runTests();
}

module.exports = runTests;